/*
    Android Asynchronous Http Client
    Copyright (c) 2013 JIXIAOLONG <MicroJixl@gmail.com>

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */
package com.jxl.netframe;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/** 
 * @author JiXL
 * @time 2013-6-9 上午11:19:07
 * this customer entity for progress.
 */
public class UploadMultipartEntity extends SimpleMultipartEntity {
	private RequestParameter rq;
	private IOBufferListener ioListener;
	
	public UploadMultipartEntity(RequestParameter rq) {
		super();
		this.rq = rq;
	}
	
	public void setIOListener(IOBufferListener ioListener) {
		this.ioListener = ioListener;
	}
	
	@Override
	public void writeTo(OutputStream outstream) throws IOException {
		super.writeTo(new CountingOutputStream(outstream,ioListener));
	}
	
	public class CountingOutputStream extends FilterOutputStream {  

		private final IOBufferListener listener;  
		private long transferred;  
		private long length = 0;

		public CountingOutputStream(OutputStream out,  
				IOBufferListener listener) {  
			super(out);  
			this.listener = listener;  
			this.transferred = 0;  
			length = UploadMultipartEntity.this.out.toByteArray().length;
		}  

		public void write(byte[] b, int off, int len) throws IOException {  
			out.write(b, off, len);  
			this.transferred += len;  
			if(listener != null)this.listener.upBufferd(rq, transferred, length);
		}  

		public void write(int b) throws IOException {  
			out.write(b);  
			this.transferred++;  
			if(listener != null)this.listener.upBufferd(rq, transferred, length); 
		}  
	}  
}
